<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="编辑商品信息"
        type="info"
        center
        show-icon>
      </el-alert>
      <!--步骤组件-->
      <el-steps :space="400" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!--tab栏标签-->
      <el-form ref="addFormRef" :model="addForm"
               :rules="addFormRules" label-position="left">
        <el-tabs tab-position="left" v-model="activeIndex"
                 :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="addForm.goodsName"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goodsPrice">
              <el-input v-model="addForm.goodsPrice" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goodsWeight">
              <el-input v-model="addForm.goodsWeight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goodsNumber">
              <el-input v-model="addForm.goodsNumber" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goodsCat">
              <el-cascader
                v-model="addForm.goodsCat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
              <el-form-item v-for="(item,i) in manyTableData" :label="item.attrName" :key="item.attrId">
                <!--复选框组-->
                <el-checkbox-group v-model="item.attrVals">
                  <el-checkbox :label="item2" v-for="(item2,i) in item.attrVals" :key="i" border></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
              <el-form-item :label="item.attrName"
                            v-for="(item,i) in onlyTableData"
                            :key="item.attrId">
                  <el-input v-model="item.attrVals"></el-input>
              </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--action 上传图片api方法-->
            <!--headers 设置el-upload 请求头参数信息-->
            <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture" :file-list="addForm.fileList"
              :headers="headersObj" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <!--<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goodsIntroduce"></quill-editor>
            <el-button type="primary" class="addButton" @click="addGoods">编辑商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!--图片对话框-->
    <el-dialog title="图片预览" :visible.sync="previewVisibleDialog" width="50%">
        <img :src="previewPath" alt="" class="previewShow">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
    export default {
        name: "Add",
      data(){
          return{
            activeIndex:'0',
            addForm:{
              goodsName:'',
              goodsPrice:0,
              goodsWeight:0,
              goodsNumber:0,
              //分类下拉框选中保存的值
              goodsCat:[],
              // //图片展示列表
              //{name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
              fileList: [],
              //商品详情介绍
              goodsIntroduce:'',
              attrs:[]
            },
            addFormRules:{
              goodsName:[{required:true,message:'请输入商品名称',trigger:'blur'}],
              goodsPrice:[{required:true,message:'请输入商品价格',trigger:'blur'}],
              goodsWeight:[{required:true,message:'请输入商品重量',trigger:'blur'}],
              goodsNumber:[{required:true,message:'请输入商品数量',trigger:'blur'}],
              goodsCat:[{required:true,message:'请输入商品分类',trigger:'blur'}]
            },
            cateList:[],
            cascaderProps: {
              expandTrigger:'hover',
              value:'catId',
              label:'catName',
              children:'children'
            },
            manyTableData:[],
            onlyTableData:[],
            //图片上传 设置请求头信息
            headersObj:{
              Authorization:window.sessionStorage.getItem("token")
            },
            previewPath:'',
            previewVisibleDialog:false
        }
      },
      created() {
        this.getCategoryList();
        this.addForm = this.$route.query;
        this.addForm.goodsCat = [this.$route.query.catOneId,this.$route.query.catTwoId,this.$route.query.catThreeId];
        this.addForm.attrs = [];
        this.addForm.fileList = [];
        //console.log(this.addForm);
      },
      methods:{
        //获取三级分类列表数据
        async getCategoryList() {
          const {data:res} = await this.$axios.get("category");
          if(res.code !=200) {
            return this.$message.error("获取三级分类失败");
          }
          this.$message.success("获取三级分类成功");
          this.cateList = res.data.resultList;
          //console.log(this.cateList);
        },
        handleChange(){
          if(this.addForm.goodsCat.length != 3) {
            this.addForm.goodsCat = [];
          }
          //console.log(this.addForm.goodsCat);
        },
        //阻止tab不完整是 切换tab 事件
        beforeTabLeave(activeName,oldActiveName) {
          //console.log("当前tab标签："+activeName,"之前tab标签："+oldActiveName);
          if(this.activeIndex == '1' && this.addForm.goodsCat.length != 3) {
            this.$message.info("请先选择商品分类");
            return false;
          }
        },
        //tab 切换点击事件
        async tabClicked(){
          //console.log(this.activeIndex);
          if(this.activeIndex == "1") {
            const {data:res} = await this.$axios.get("attributeList/"+this.catId,
              {params:{attrSel:'many'}});
            if(res.code != 200) {
              return this.$message.error("根据分类获取动态参数失败");
            }
            this.$message.success("根据分类获取动态参数成功");
            //console.log(res.data);
            res.data.forEach(item=>{
              item.attrVals = item.attrVals?item.attrVals.split(" "):[];
            })
            this.manyTableData = res.data;
            console.log(this.manyTableData);
          } else if(this.activeIndex == "2") {
            const {data:res} = await this.$axios.get("attributeList/"+this.catId,
              {params:{attrSel:'only'}});
            if(res.code != 200) {
              return this.$message.error("根据分类获取静态属性失败");
            }
            this.$message.success("根据分类获取静态属性成功");
            this.onlyTableData = res.data;
            //console.log(this.onlyTableData);
          }
        },
        //处理预览图片事件
        handlePreview(file){
          //file 从服务器返回获取图片url
          this.previewPath = 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100';
          this.previewVisibleDialog = true;
        },
        //处理图片移除事件
        handleRemove(file){
            //获取移除图片路径（服务器后端返回）
            const filePath = 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100';
            //从fileList 数组找到删除图片的下标
            const i = this.addForm.fileList.findIndex(x=>
              x.url == filePath);
            //调用数组 splice 方法，把图片信息对象从fileList数组移除
            this.addForm.fileList.splice(i,1);
            //console.log(this.addForm.fileList);
        },
        //图片上传成功回调函数
        handleSuccess(response){
          //console.log(response);
          const picInfo = {name:'ss.jpg',url:'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'};
          //保存图片集合
          this.addForm.fileList.push(picInfo);
        },
        //添加商品方法
        addGoods(){
          this.$refs.addFormRef.validate(async valid=>{
            if(!valid) {
              this.$message.error("请输入必要的填项")
              return;
            }
            console.log(this.addForm);
            //把原有对象拷贝到新的对象中
            const form  = _.cloneDeep(this.addForm);
            form.goodsCat = form.goodsCat.join(",");
            //处理动态属性参数
            this.manyTableData.forEach(item=>{
              if(item.attrVals != "") {
                const newInfo = {
                  attrId:item.attrId,
                  attrVals:item.attrVals.join(" ")
                };
                this.addForm.attrs.push(newInfo);
              }
            });
            //console.log(this.addForm);
            //处理静态属性参数
            this.onlyTableData.forEach(item=>{
              if(item.attrVals != "") {
                const newInfo = {
                  attrId: item.attrId,
                  attrVals: item.attrVals
                };
                this.addForm.attrs.push(newInfo);
              }
            });
            form.attrs = this.addForm.attrs;
            console.log(form);
            const {data:res} = await this.$axios.post("update/goods",form);
            //console.log(res);
            if(res.code != 200) {
              return this.$message.error("编辑商品失败");
            }
            this.$message.success("编辑商品成功");
            this.$router.push("/goods");
          })
        }
      },

      //计算属性方法
      computed:{
          //分类id
          catId(){
            if(this.addForm.goodsCat.length == 3) {
              return this.addForm.goodsCat[2];
            }
            return null;
          }
      }
    }
</script>

<style scoped>

  .el-checkbox{
    margin: 0 5px 0 0 !important;
  }
  .previewShow{
    width: 100%;
  }
.addButton{
  margin-top: 15px;
}
</style>
